import to from "await-to-js";
import { computed, reactive } from "vue"

export default () => {
  const state = reactive({
    columns: [],
    dataSource: [] as any[],
    loading: false,
    pagination: {
      total: 0,
      current: 1,
      pageSize: 15,
    },
    selectedRowKeys: []
  })
  const defineColumns = (columns) => {
    state.columns = columns || [];
  }
  const rowSelection = computed(() => {
    return {
      selectedRowKeys: state.selectedRowKeys,
      fixed: true,
      onChange: (changableRowKeys) => {
        state.selectedRowKeys = changableRowKeys;
      }
    }
  })
  //获取同步列表信息
  const setDataSource = (dataSource) => {
    state.dataSource = dataSource || [];
  }
  //获取异步列表信息(接口请求)
  const setSyncDataSource = async (fetch, e?: { success?: (res: any) => void, error?: (err: any) => void }) => {
    state.loading = true;
    const [err, res]: any = await to(fetch());
    if (!err) {
      state.dataSource = res.data || [];
      e?.success?.(res);
    } else {
      e?.error?.(err);
    }
    state.loading = false;
  }
  const getIndex = (idx) => {
    return (state.pagination.current - 1) * state.pagination.pageSize + idx + 1;
  }
  return {
    state,
    defineColumns,
    setDataSource,
    setSyncDataSource,
    rowSelection,
    getIndex,
  }
}